import { useLocalStorageState } from 'ahooks';

type SetValue<T> = (value: T | ((prevValue: T) => T)) => void;

export function useLocalState<T>(
  key: string,
  initialValue: T,
  options?: {
    serializer?: (value: T) => string;
    deserializer?: (value: string) => T;
  },
): [T, SetValue<T>] {
  const [state, rawSetState] = useLocalStorageState<T>(key, {
    defaultValue: initialValue,
    serializer: options?.serializer,
    deserializer: options?.deserializer,
  });
  const setState: (value: T | ((prevValue: T) => T)) => void = (value) => {
    if (typeof value === 'function') {
      rawSetState((prev: T) => {
        const prevSafe = (prev === undefined ? initialValue : prev) as T;
        return (value as (prevValue: T) => T)(prevSafe);
      });
    } else {
      rawSetState(value);
    }
  };
  return [state, setState];
}
